package com.neuedu.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Component
public class AliOssUtils {
    @Autowired
    private OSS ossClient;
    //-图片上传
    public String upload(MultipartFile multipartFile){
        String fileName = multipartFile.getOriginalFilename();
        String filePath =getFilePath(fileName);
        try{
            ossClient.putObject("neuedushopping",filePath,new ByteArrayInputStream(multipartFile.getBytes()));

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());

            calendar.add(Calendar.YEAR,10);
            //图片存储成功之后返回，图片的url
            URL url = ossClient.generatePresignedUrl("neuedushopping",filePath,calendar.getTime());
            return url.toString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return "";
    }
    private static String getFilePath(String sourceFileName){
        String suffix = sourceFileName.substring(sourceFileName.indexOf(".")+1);
        String fileName = UUID.randomUUID().toString()+"."+suffix;
        DateTime dateTime = new DateTime();
        String path = fileName;
        return path;
    }
}
